from flaskapp.util.Sqlalchemy import db

class Orders(db.Model):
    __tablename__ = 'orders'

    rent_id = db.Column(db.Integer, primary_key=True)
    tenant_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False)
    landlord_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), nullable=False)
    house_id = db.Column(db.Integer, db.ForeignKey('house.house_id'), nullable=False)
    start_date = db.Column(db.Date, nullable=False)
    rental_months = db.Column(db.Integer, nullable=False)
    monthly_rent = db.Column(db.Numeric(10, 2), nullable=False)
    end_date = db.Column(db.Date, nullable=False)
    amount = db.Column(db.Numeric(10, 2), nullable=False)
    payment_status = db.Column(db.Enum('未支付', '已支付', '部分支付'), default='未支付')
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())

    def __init__(self, tenant_id, landlord_id, house_id, start_date, rental_months, monthly_rent, amount):
        self.tenant_id = tenant_id
        self.landlord_id = landlord_id
        self.house_id = house_id
        self.start_date = start_date
        self.rental_months = rental_months
        self.monthly_rent = monthly_rent
        self.amount = amount
        # end_date is calculated by the database

    def to_dict(self):
        return {
            'rent_id': self.rent_id,
            'tenant_id': self.tenant_id,
            'landlord_id': self.landlord_id,
            'house_id': self.house_id,
            'start_date': self.start_date.isoformat(),
            'rental_months': self.rental_months,
            'monthly_rent': float(self.monthly_rent),
            'end_date': self.end_date.isoformat(),
            'amount': float(self.amount),
            'payment_status': self.payment_status,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }